package com.monkeyboy.service.rockettransaction;

import com.alibaba.fastjson.JSON;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @Author Gavin
 * @date 2020.08.22 10:54
 */
@Component
@RocketMQTransactionListener
public class OrderTransactionListener implements RocketMQLocalTransactionListener {

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        try {
            System.out.println("开始执行本地事务---------------------");
            String msg = new String((byte[]) message.getPayload());
            Map map = JSON.toJavaObject(JSON.parseObject(msg), Map.class);
            System.out.println(map);
            Map<String,Object> args= (Map<String, Object>) o;
            System.out.println("额外传递的参数：--------"+JSON.toJSONString(args));
        } catch (Exception e) {//如果发生了异常那么就回滚消息
            e.printStackTrace();
            System.out.println("出现异常--------------事务开始回滚");
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        System.out.println("事务执行完毕，提交事务成功----------------------");
        return RocketMQLocalTransactionState.COMMIT;
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        System.out.println("消息回查------------------");
        return RocketMQLocalTransactionState.COMMIT;
    }
}
